package cn.ecut.servlet;

import org.apache.jasper.runtime.HttpJspBase;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.HttpJspPage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @Author ruanxin
 */
//保存上一次用户访问时间
public class CookieDemo01 extends HttpServlet  {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器告诉你，你来的时间，把时间封装成一个信封，下次再来的时候带上信封，我就知道你来了

        //解决中文乱码问题
        resp.setCharacterEncoding("GBK");
        req.setCharacterEncoding("GBK");


        PrintWriter out = resp.getWriter();

        //Cookie，从服务端获取
        Cookie[] cookies = req.getCookies();

        if (cookies != null) {
            //如果存在
            out.write("你上一次访问的时间是:");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if ("lastLoginTime".equals(cookie.getName())){
                    //获取Cookie中的值
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
            }
        } else {
            out.write("这是您第一次访问");
        }

        //服务端给客户端响应一个Cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        //设置cookie有效期
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
